export class BaseController {
    constructor(model) {
        this.model = model;
    }

    /**
     * 通用分页获取数据
     * @param {Object} options - 查询选项
     * @returns {Promise<Object>} 分页结果
     */
    async getPaginatedData(options = {}) {
        try {
            const {
                page = 1,
                limit = 10,
                search,
                filters = {},
                tableName,
                searchFields = [],
                selectFields = '*',
                orderBy = 'created_at DESC'
            } = options;

            const offset = (page - 1) * limit;
            
            // 构建查询条件
            const whereConditions = [];
            const whereParams = [];
            
            // 添加搜索条件
            if (search && searchFields.length > 0) {
                const searchConditions = searchFields.map(field => `${field} LIKE ?`);
                whereConditions.push(`(${searchConditions.join(' OR ')})`);
                searchFields.forEach(() => whereParams.push(`%${search}%`));
            }
            
            // 添加筛选条件
            Object.entries(filters).forEach(([key, value]) => {
                if (value !== undefined && value !== null) {
                    whereConditions.push(`${key} = ?`);
                    whereParams.push(value);
                }
            });
            
            const whereClause = whereConditions.length > 0 ? whereConditions.join(' AND ') : '1=1';
            
            // 获取数据
            const data = await this.model.findAll(tableName, {
                select: selectFields,
                where: whereClause,
                whereParams: [...whereParams, limit, offset],
                orderBy,
                limit,
                offset
            });
            
            // 获取总数
            const total = await this.model.count(tableName, {
                where: whereClause,
                params: whereParams.slice(0, -2) // 移除limit和offset参数
            });
            
            const totalPages = Math.ceil(total / limit);
            
            return {
                data,
                pagination: {
                    page,
                    limit,
                    total,
                    totalPages
                }
            };
        } catch (error) {
            throw new Error(`Failed to get paginated data: ${error.message}`);
        }
    }

    /**
     * 通用根据ID获取数据
     * @param {string} tableName - 表名
     * @param {number|string} id - 记录ID
     * @param {string} selectFields - 选择字段
     * @returns {Promise<Object|null>} 查询结果
     */
    async getById(tableName, id, selectFields = '*') {
        try {
            if (!this._isValidId(id)) {
                throw new Error('Invalid ID provided');
            }
            
            return await this.model.findById(tableName, id, selectFields);
        } catch (error) {
            throw new Error(`Failed to get record by ID: ${error.message}`);
        }
    }

    /**
     * 通用创建数据
     * @param {string} tableName - 表名
     * @param {Object} data - 创建数据
     * @param {Function} validator - 验证函数
     * @returns {Promise<Object>} 创建结果
     */
    async create(tableName, data, validator = null) {
        try {
            // 数据验证
            if (validator && typeof validator === 'function') {
                await validator(data);
            }
            
            // 添加时间戳
            const createData = {
                ...data,
                created_at: new Date(),
                updated_at: new Date()
            };
            
            const result = await this.model.create(tableName, createData);
            
            // 返回创建的记录
            if (result.insertId) {
                return await this.getById(tableName, result.insertId);
            }
            
            return result;
        } catch (error) {
            throw new Error(`Failed to create record: ${error.message}`);
        }
    }

    /**
     * 通用更新数据
     * @param {string} tableName - 表名
     * @param {number|string} id - 记录ID
     * @param {Object} data - 更新数据
     * @param {Function} validator - 验证函数
     * @returns {Promise<Object>} 更新结果
     */
    async update(tableName, id, data, validator = null) {
        try {
            if (!this._isValidId(id)) {
                throw new Error('Invalid ID provided');
            }
            
            // 检查记录是否存在
            const existingRecord = await this.getById(tableName, id);
            if (!existingRecord) {
                throw new Error('Record not found');
            }
            
            // 数据验证
            if (validator && typeof validator === 'function') {
                await validator(data, id);
            }
            
            // 添加更新时间戳
            const updateData = {
                ...data,
                updated_at: new Date()
            };
            
            await this.model.update(tableName, id, updateData);
            
            // 返回更新后的记录
            return await this.getById(tableName, id);
        } catch (error) {
            throw new Error(`Failed to update record: ${error.message}`);
        }
    }

    /**
     * 通用删除数据
     * @param {string} tableName - 表名
     * @param {number|string} id - 记录ID
     * @param {boolean} soft - 是否软删除
     * @returns {Promise<Object>} 删除结果
     */
    async delete(tableName, id, soft = false) {
        try {
            if (!this._isValidId(id)) {
                throw new Error('Invalid ID provided');
            }
            
            // 检查记录是否存在
            const existingRecord = await this.getById(tableName, id);
            if (!existingRecord) {
                throw new Error('Record not found');
            }
            
            if (soft) {
                return await this.model.softDelete(tableName, id);
            } else {
                return await this.model.delete(tableName, id);
            }
        } catch (error) {
            throw new Error(`Failed to delete record: ${error.message}`);
        }
    }

    /**
     * 批量更新状态
     * @param {string} tableName - 表名
     * @param {Array} ids - 记录ID数组
     * @param {string} status - 新状态
     * @param {string} statusField - 状态字段名
     * @returns {Promise<Object>} 更新结果
     */
    async batchUpdateStatus(tableName, ids, status, statusField = 'status') {
        try {
            if (!Array.isArray(ids) || ids.length === 0) {
                throw new Error('IDs must be a non-empty array');
            }
            
            // 验证所有ID
            ids.forEach(id => {
                if (!this._isValidId(id)) {
                    throw new Error(`Invalid ID: ${id}`);
                }
            });
            
            return await this.model.batchUpdateStatus(tableName, ids, status, statusField);
        } catch (error) {
            throw new Error(`Failed to batch update status: ${error.message}`);
        }
    }

    /**
     * 验证必填字段
     * @param {Object} data - 数据对象
     * @param {Array} requiredFields - 必填字段数组
     * @throws {Error} 验证失败时抛出错误
     */
    _validateRequiredFields(data, requiredFields) {
        const missingFields = [];
        
        requiredFields.forEach(field => {
            if (!data.hasOwnProperty(field) || data[field] === undefined || data[field] === null || data[field] === '') {
                missingFields.push(field);
            }
        });
        
        if (missingFields.length > 0) {
            throw new Error(`Missing required fields: ${missingFields.join(', ')}`);
        }
    }

    /**
     * 验证字段长度
     * @param {Object} data - 数据对象
     * @param {Object} lengthRules - 长度规则对象
     * @throws {Error} 验证失败时抛出错误
     */
    _validateFieldLengths(data, lengthRules) {
        Object.entries(lengthRules).forEach(([field, rules]) => {
            if (data[field] !== undefined && data[field] !== null) {
                const value = String(data[field]);
                
                if (rules.min && value.length < rules.min) {
                    throw new Error(`${field} must be at least ${rules.min} characters long`);
                }
                
                if (rules.max && value.length > rules.max) {
                    throw new Error(`${field} must not exceed ${rules.max} characters`);
                }
            }
        });
    }

    /**
     * 验证邮箱格式
     * @param {string} email - 邮箱地址
     * @returns {boolean} 是否有效
     */
    _isValidEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }

    /**
     * 验证手机号格式
     * @param {string} phone - 手机号
     * @returns {boolean} 是否有效
     */
    _isValidPhone(phone) {
        const phoneRegex = /^1[3-9]\d{9}$/;
        return phoneRegex.test(phone);
    }

    /**
     * 验证ID格式
     * @param {*} id - ID值
     * @returns {boolean} 是否有效
     */
    _isValidId(id) {
        return id && (typeof id === 'number' || (typeof id === 'string' && /^\d+$/.test(id)));
    }

    /**
     * 验证数值范围
     * @param {number} value - 数值
     * @param {number} min - 最小值
     * @param {number} max - 最大值
     * @returns {boolean} 是否在范围内
     */
    _isInRange(value, min, max) {
        return value >= min && value <= max;
    }

    /**
     * 清理数据对象，移除undefined和null值
     * @param {Object} data - 数据对象
     * @returns {Object} 清理后的数据对象
     */
    _cleanData(data) {
        const cleaned = {};
        Object.entries(data).forEach(([key, value]) => {
            if (value !== undefined && value !== null) {
                cleaned[key] = value;
            }
        });
        return cleaned;
    }

    /**
     * 生成随机字符串
     * @param {number} length - 字符串长度
     * @param {string} charset - 字符集
     * @returns {string} 随机字符串
     */
    _generateRandomString(length = 8, charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
        let result = '';
        for (let i = 0; i < length; i++) {
            result += charset.charAt(Math.floor(Math.random() * charset.length));
        }
        return result;
    }

    /**
     * 格式化日期
     * @param {Date} date - 日期对象
     * @param {string} format - 格式字符串
     * @returns {string} 格式化后的日期字符串
     */
    _formatDate(date = new Date(), format = 'YYYY-MM-DD HH:mm:ss') {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        
        return format
            .replace('YYYY', year)
            .replace('MM', month)
            .replace('DD', day)
            .replace('HH', hours)
            .replace('mm', minutes)
            .replace('ss', seconds);
    }

    /**
     * 记录操作日志
     * @param {string} action - 操作类型
     * @param {string} tableName - 表名
     * @param {*} recordId - 记录ID
     * @param {Object} details - 详细信息
     */
    _logOperation(action, tableName, recordId, details = {}) {
        const logEntry = {
            timestamp: new Date().toISOString(),
            action,
            table: tableName,
            recordId,
            details
        };
        
        // 这里可以扩展为写入日志文件或数据库
        console.log('Operation Log:', JSON.stringify(logEntry, null, 2));
    }
}